using System.Collections.Generic;
using SqlQueryBuilder.Clauses;
using SqlQueryBuilder.Util;

namespace SqlQueryBuilder.Criterias
{
    /// <summary>
    /// Select Criteria
    /// </summary>
    public class Select : ICriteria
    {
        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether [select all].
        /// </summary>
        /// <value><c>true</c> if [select all]; otherwise, <c>false</c>.</value>
        public bool selectAll { get; set; }
        
        /// <summary>
        /// Gets or sets the select clauses.
        /// </summary>
        /// <value>The select clauses.</value>
        public List<SelectClause> selectClauses { get; set; }
        
        /// <summary>
        /// Gets or sets the Top Criteria.
        /// </summary>
        /// <value>The top.</value>
        public Top top { get; set; }

        /// <summary>
        /// Containes distinct clause or not
        /// </summary>
        public bool isDistinct;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Select"/> class.
        /// </summary>
        public Select()
        {
            top = null;
            selectAll = false;
            selectClauses = new List<SelectClause>();
        }

        #endregion
        
        /// <summary>
        /// Builds the criteria.
        /// </summary>
        /// <returns></returns>
        public string BuildCriteria()
        {
            string beginSelect = "SELECT";
            if (top != null)
                beginSelect += string.Format(" TOP {0}", top.Value);

            if (isDistinct)
                beginSelect += " DISTINCT ";

            if (selectAll)
                return string.Format("{0} * ", beginSelect);

            return string.Format("{0} {1} ", beginSelect, GenerateSelectClause());
        }

        /// <summary>
        /// Generates the select clause.
        /// </summary>
        /// <returns></returns>
        private string GenerateSelectClause() {
            bool firstClause = true;
            string select = string.Empty;
            foreach (var selectClause in selectClauses)
            {
                if (firstClause)
                    firstClause = false;
                else
                    select = SqlMultipleFields.AddSeparator(select);

                if (!string.IsNullOrEmpty(selectClause.Alias))
                    select += string.Format("{0} AS {1} ", selectClause.selectClause, selectClause.Alias);
                else
                    select += string.Format("{0} ", selectClause.selectClause);
            }
            return select;
        }
    }
}